﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Rodunu.Business.Interfaces;
using Rodunu.Business.Models.User;
using Rodunu.Services.Interfaces;
using Rodunu.Services.NetFlix;

namespace Rodunu.Clients.WPF.Services.Netflix
{
    /// <summary>
    /// Interaction logic for DetailPage.xaml
    /// </summary>
    public partial class DetailPage
    {
        private INetFlixService _netFlixService;
        private readonly IManageSettings _manageSettings;
        private readonly Account _account;

        public DetailPage(IManageSettings manageSettings)
        {
            InitializeComponent();

            _manageSettings = manageSettings;

            LogInOutButton.Click += LogInOutButton_Click;
            CloseButton.Click += CloseButton_Click;

            if (_manageSettings.CurrentUser != null)
            {
                _account = (from act in _manageSettings.CurrentUser.Accounts
                            where act.AccountType == AccountTypes.Netflix
                            select act).SingleOrDefault();
                if (_account == null)
                {
                    _account = new Account();
                    _account.AccountType = AccountTypes.Netflix;
                    _manageSettings.CurrentUser.Accounts.Add(_account);
                }
            }

            _account.AccountType = AccountTypes.Netflix;
            UserNameTextBox.Text = _account.Login;
            PasswordTextBox.Password = _account.Password;
            IsEnabledCheckBox.IsChecked = _account.IsEnabled;
        }

        void CloseButton_Click(object sender, RoutedEventArgs e)
        {
            _account.AccountType = AccountTypes.Netflix;
            _account.Login = UserNameTextBox.Text;
            _account.Password = PasswordTextBox.Password;
            _account.IsEnabled = (bool) IsEnabledCheckBox.IsChecked;

            _manageSettings.SaveCurrentSettings();
        }

        void LogInOutButton_Click(object sender, RoutedEventArgs e)
        {
            Cursor = Cursors.Wait;
            try
            {
                _netFlixService =
                new NetFlixService(UserNameTextBox.Text, PasswordTextBox.Password);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                Cursor = Cursors.Arrow;
                return;
            }
            MessageBox.Show("Signed in successfully!");
            LogInOutButton.Content = "Sign Out";
            Cursor = Cursors.Arrow;
        }
    }
}